package cn.iocoder.yudao.framework.common.util.id;

import cn.hutool.core.util.IdUtil;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 自增唯一id
 */
public class IdUtils {


    /**
     * 生成自增唯一id
     *
     * @return
     */
    public static String generatorId() {
        final String id = IdUtil.objectId();
        return id;
    }

    public static void main(String[] args) throws Exception {
        // 方法1：snowflake，短时间内生成多次会重复
//        for (int i = 0; i < 100; i++) {
//            Snowflake snowflake = IdUtil.createSnowflake(1, 1);
//            long id1 = snowflake.nextId();
//            System.out.println("id1: " + id1);
//        }

        System.out.println("==========================");

        final ExecutorService executor = Executors.newFixedThreadPool(128);
        final int count = 1000000;
        final CountDownLatch latch = new CountDownLatch(count);
        final Set<String> ids = Collections.synchronizedSet(new HashSet<>());

        // 方法2：IdUtil.objectId()
        for (int i = 0; i < count; i++) {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        final String id2 = IdUtil.objectId();
                        System.out.println(id2);

                        final boolean add = ids.add(id2);
                        if (!add) {
                            throw new RuntimeException("重复：" + id2);
                        }
                    } finally {
                        latch.countDown();
                    }
                }
            });
        }
        latch.await();

        System.out.println("ids.size: " + ids.size());
    }


}
